package com.mid;

/**
 * Created by Lxk on 2019/7/14.
 */
public class Solution725 {

    public ListNode[] splitListToParts(ListNode root, int k) {
        ListNode[] res = new ListNode[k];
        if(root==null){
            return res;
        }
        int count = 0;
        ListNode cur = root;
        while(cur!=null){
            cur = cur.next;
            count++;
        }
        boolean rightFlag = false;
        int biggerLen = 0,biggerCount = 0;
        if(count%k==0){
            rightFlag = true;
            biggerLen = count/k;
            biggerCount = k;
        }else{
            biggerLen = (count/k) + 1;
            biggerCount = count - (biggerLen-1)*((biggerLen==1)?0:count/(biggerLen-1));
        }
        int resPos = 0;
        int i = 0;
        for(cur = root; cur!=null; i++){
            //已經到biggerLen-1
            if(i/biggerLen>=biggerCount){
                if((i-biggerLen*biggerCount)%(biggerLen-1) == 0){
                    res[resPos++] = cur;
                    cur = cur.next;
                }else if((i-biggerLen*biggerCount)%(biggerLen-1) == (biggerLen-2)){
                    ListNode temp = cur;
                    cur = cur.next;
                    temp.next = null;
                }
            }else{
                //在biggerLen
                if(i%biggerLen==0){
                    res[resPos++] = cur;
                    cur = cur.next;
                }else if(i%biggerLen == (biggerLen-1)){
                    ListNode temp = cur;
                    cur = cur.next;
                    temp.next = null;
                }
            }
        }
        return res;
    }

}
